package com.tencent.tmm.knoi.sample

import com.tencent.tmm.knoi.annotation.ServiceProvider
import com.tencent.tmm.knoi.type.JSValue

@ServiceProvider(singleton = true)
open class IWorkProvider {
    fun testCallback(callback: (Array<JSValue?>) -> Any?): Int {
        val params = arrayOf<JSValue?>(
            JSValue.createJSValue(6),
            JSValue.createJSValue("hahaha")
        )
        val firstReadable = params[0]?.toInt()
        val secondReadable = params[1]?.toKString()
        LogUtil.d(
            "testCallback",
            "invoke callback hash=${callback.hashCode()} params0=$firstReadable params1=$secondReadable"
        )
        val result: Any? = callback.invoke(params)
        LogUtil.d(
            "testCallback",
            "callback result type=${result?.let { it::class.simpleName }} value=$result"
        )
        val resultHexDecimal = result.toHexHashDecimalOrNull()
        LogUtil.d("testCallback", "knoi-sample testCalllback rawHexDecimal= $resultHexDecimal")
        val r3 = result.toCallbackInt()
        val readable = when (result) {
            is JSValue -> result.toKString().takeUnless { it.isNullOrEmpty() } ?: result.toInt().toString()
            else -> result?.toString()
        }
        LogUtil.d("testCallback", "testCallback normalizeInt=$r3 rawString=$readable")
        return r3
    }
}

private fun Any?.toCallbackInt(): Int {
    return when (this) {
        is Int -> this
        is Double -> this.toInt()
        is Long -> this.toInt()
        is JSValue -> this.toInt()
        null -> 0
        else -> error("Unsupported JS callback return type: ${this::class}")
    }
}

private fun Any?.toHexHashDecimalOrNull(): Int? {
    val raw = this?.toString() ?: return null
    val hexPart = raw.substringAfter('@', missingDelimiterValue = "")
    if (hexPart.isEmpty()) return null
    return runCatching { hexPart.toLong(16).toInt() }.getOrNull()
}
